import { requestBase } from "../utils/request";
import { wxPromise } from "../utils/utils";

/**
 * 微信登录
 */
export function login() {
    wx.showLoading({
        title: '正在登录中',
        mask: true
    })
    return wxPromise(wx.login)
        .then(data => {
            return requestBase('api/login', {
                code: res.data
            })
        })
        .then(data => {
            wx.hideLoading()
            wx.setStorageSync('token', data.data.data.token)
            return Promise.resolve(data.data.data)
        }).catch(() => {
            wx.hideLoading()
            return Promise.reject(1)
        })
}

/**
 * 注册 前提有getUserInfo权限
 * @param params
 * @param callback
 */
export function register(params, callback) {
    let code = null
    return wxPromise(wx.login)
        .then(codeData => {
            code = codeData.code
            return wxPromise(wx.getUserInfo, {
                withCredentials: true,
            })
        })
        .catch(() => {
            wx.showToast({
                title: '请同意获取用户信息，以便为您注册',
                icon: 'none'
            })
        })
        .then(data => {
            return requestBase('api/register', {
                ...params,
                iv: data.iv,
                encrypted_data: data.encryptedData,
                code
            })
        }).then(data => {
            wx.setStorageSync('token', data.data.data.token)
            return '1'
        })
}

/**
 * 获取用户信息
 */
export function getUserInfo() {
    if (wx.getStorageSync('token')) {
        return requestBase('api/userinfo').then(data => {
            wx.setStorageSync('userInfo', data.data.data)
            // 监听userInfo变化更新
            getCurrentPages()
                .filter(item => item.watchUserInfo)
                .forEach(component => component.setData({
                    userInfo: data.data.data
                }))
            return data.data.data
        })
    }
}

/**
 * 从本地绑定用户信息
 * @param components
 */
export function bindUserInfo(components) {
    const data = wx.getStorageSync('userInfo')
    components.watchUserInfo = true
    components.setData({
        userInfo: data ? data : null
    })
}
